import axios from 'axios';
import qs from 'qs';
import store from '@/store'
import { Message } from 'element-ui';

export default {
    install(Vue) {
        let baseUrl = ''; // 填写 baseUrl
        // if (location.host.indexOf('localhost') > -1) {
        //     baseUrl = '/gateway';
        // } else if (location.host.indexOf('test') > -1) {
        //     baseUrl = 'http://ovo.test.chinawayltd.com/gateway';
        // }

        const ax = axios.create({
            baseURL: baseUrl,
            transformRequest: [function (data) {
                return qs.stringify(data);
            }],
        });

        ax.interceptors.request.use((config) => {
            if (!store.state.isLogin) {
                Vue.$pub.login();
            }
            return config; 
        }, error => Promise.reject(error));

        ax.interceptors.response.use((response) => {
            // 特定错误码的统一处理
            const code = response.data.code;
            if (code === 0) {
                return response.data.data;
            }
            const message = response.data.msg;
            
            switch (code) {
                case 401:
                    Vue.$pub.login();
                    break;
            }
            // 统一提示接口业务错误
            if (message) {
                Message({
                    type: 'error',
                    message: message ? message : '接口错误',
                    duration: 8000,
                })
            }
            
            return Promise.reject(new Error(message));
        }, (error) => {
            let message = error.msg;
            if (error.response) {
                if (error.response.data && error.response.data.msg) {
                   message = error.response.data.msg;
                }
                const status = error.response.status;
                switch (status) {
                    // 未登录
                    case 401:
                        Vue.$pub.login();
                        break;
                    default:
                }
            }
            // 统一提示接口业务错误
            // if (message) {
            Message({
                type: 'error',
                message: message ? message : '接口错误',
                duration: 8000,
            })
            // }

            return Promise.reject(error);
        });

        Vue.$axios = Vue.prototype.$axios = ax;
    },
};
